/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.equipment.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.I18nUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentCommand;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentLog;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentCommandService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentLogService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

/**
 * 设备日志Controller
 * @author unnamed
 * @version 2017-07-05
 */
@Controller
@RequestMapping(value = "${adminPath}/equipment/eleEquipmentLog")
public class EleEquipmentLogController extends BaseController {

	@Autowired
	private EleEquipmentLogService eleEquipmentLogService;
	@Autowired
	private EleEquipmentService eleEquipmentService;
	@Autowired
	private EleEquipmentCommandService eleEquipmentCommandService;
	@ModelAttribute
	public EleEquipmentLog get(@RequestParam(required=false) String id) {
		EleEquipmentLog entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eleEquipmentLogService.get(id);
		}
		if (entity == null){
			entity = new EleEquipmentLog();
		}
		return entity;
	}
	
	@RequiresPermissions("equipment:eleEquipment:view")
	@RequestMapping(value = {"list", ""})
	public String list(EleEquipmentLog eleEquipmentLog, HttpServletRequest request, HttpServletResponse response, Model model) {
		String type = request.getParameter("type");
		String equipmentId = request.getParameter("equipmentId");
		eleEquipmentLog.setType(type);
		eleEquipmentLog.setEquipmentId(equipmentId);
		//EleEquipment eq = eleEquipmentService.get(equipmentId);
		//createCommandForLog(eq,type);
		Page<EleEquipmentLog> page = eleEquipmentLogService.findPage(new Page<EleEquipmentLog>(request, response), eleEquipmentLog); 
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
		model.addAttribute("page", page);
		model.addAttribute("type", type);
		model.addAttribute("equipmentId", equipmentId);
		return "modules/equipment/eleEquipmentLogList";
	}
	
	private void createCommandForLog(EleEquipment eq,String type){
		List<EleEquipmentCommand> commandsList = eleEquipmentCommandService.findListByEquipmentId(eq.getId(), EleEquipmentCommand.DEL_FLAG_NORMAL,type);
		if(commandsList.size() > 0){
			eleEquipmentCommandService.batchDelete(commandsList, EleEquipmentCommand.DEL_FLAG_DELETE);
		}
		EleEquipmentCommand eec = new EleEquipmentCommand();
		eec.setEquipmentId(eq.getId());
		eec.setType(type);
		eec.setDelFlag(EleEquipmentCommand.DEL_FLAG_NORMAL);
		eleEquipmentCommandService.save(eec);
	}

	@RequiresPermissions("equipment:eleEquipment:view")
	@RequestMapping(value = "form")
	public String form(EleEquipmentLog eleEquipmentLog, Model model) {
		model.addAttribute("eleEquipmentLog", eleEquipmentLog);
		return "modules/equipment/eleEquipmentLogForm";
	}
	@RequiresPermissions("equipment:eleEquipment:view")
	@RequestMapping(value = "viewPic")
	public String viewPic(HttpServletRequest request, Model model) {
		String logId = request.getParameter("logId");
		EleEquipmentLog eleEquipmentLog = eleEquipmentLogService.get(logId);
		model.addAttribute("eleEquipmentLog", eleEquipmentLog);
		return "modules/equipment/eleEquipmentLogView";
	}
	@RequiresPermissions("equipment:eleEquipment:view")
	@RequestMapping(value = "save")
	public String save(EleEquipmentLog eleEquipmentLog, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, eleEquipmentLog)){
			return form(eleEquipmentLog, model);
		}
		eleEquipmentLogService.save(eleEquipmentLog);
		String locale = I18nUtils.getLocaleStr();
		String msg = "保存设备日志成功";
		if(Global.US.equals(locale)){
			msg = "Equipment log saved";
		}
		addMessage(redirectAttributes, msg);
		/*return "redirect:"+Global.getAdminPath()+"/source/floor/eleSourceFloored/?repage";
		addMessage(redirectAttributes, "保存设备日志成功");*/
		return "redirect:"+Global.getAdminPath()+"/equipment/eleEquipmentLog/?repage";
	}
	
	@RequiresPermissions("equipment:eleEquipment:edit")
	@RequestMapping(value = "deleteLog")
	@ResponseBody
	public Result delete(HttpServletRequest request, RedirectAttributes redirectAttributes) {
		EleEquipmentLog eleEquipmentLog = eleEquipmentLogService.get(request.getParameter("logId"));
		eleEquipmentLogService.delete(eleEquipmentLog);
		String locale = I18nUtils.getLocaleStr();
		String msg = "成功删除";
		if(Global.US.equals(locale)){
			msg = "Delete success";
		}

        return new Result(Result.SUCCESS, msg, null);

	}
	@RequiresPermissions("equipment:eleEquipment:view")
	@RequestMapping(value = "sync")
	@ResponseBody
	public Result sync(HttpServletRequest request,RedirectAttributes redirectAttributes) {
		String eqId = request.getParameter("equipmentId");
		String type = request.getParameter("type");
		EleEquipment eq = eleEquipmentService.get(eqId);
		createCommandForLog(eq,type);
		String locale = I18nUtils.getLocaleStr();
		String msg = "同步完成";
		if(Global.US.equals(locale)){
			msg = "Synchronizing completion";
		}
        return new Result(Result.SUCCESS, msg, null);

	}
	@RequiresPermissions("equipment:eleEquipment:view")
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String logId = request.getParameter("logId");
		EleEquipmentLog eleEquipmentLog = eleEquipmentLogService.get(logId);
		String tmpPath = eleEquipmentLog.getPath();
		String name = eleEquipmentLog.getName();
		downloadFile(Global.getUserfilesBaseDir()+tmpPath,name,response);
		
	}
	public void downloadFile(String filePath, String fileName,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		// response.setContentType("application/octet-stream");

		try {
			File file = new File(filePath);
			// 以流的形式下载文件。
			BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			toClient.write(buffer);
			toClient.flush();
			toClient.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}